﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using vuonthieunhi.Models;
using vuonthieunhi.Areas.Administration.Models;
using vuonthieunhi.Library;

namespace TSV.Areas.Administration.Controllers
{
    public class AuthenticateController : Controller
    {
        protected AuthenticateDao auDao = new AuthenticateDao();

        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection collection)
        {
            if (String.IsNullOrEmpty(collection["username"]) || String.IsNullOrEmpty(collection["password"]))
            {
                ViewData["ErrorDetails"] = Resources.Message.E0001;

                return View();
            }

            var userName = collection["username"];
            var password = collection["password"];

            if (!Authenticate(userName, password))
                return View();

            var logonUser = auDao.GetUserByName(userName);

            DoLogin(logonUser);

            string urlParam = Request["ReturnUrl"];
            string roleParam = Request["role"];

            if (!string.IsNullOrEmpty(urlParam))
            {
                return Redirect(urlParam);
            }
            return RedirectToAction("Index", "Partner");

        }

        #region Helper methods

        [NonAction()]
        private bool Authenticate(string username, string password)
        {
            ViewData["ErrorDetails"] = string.Empty;
            var fieldAuthenticated = true;
            if (String.IsNullOrEmpty(username))
            {
                fieldAuthenticated = false;

            }
            if (String.IsNullOrEmpty(password))
            {
                fieldAuthenticated = false;

            }

            if (!Login(username, password))
            {
                fieldAuthenticated = false;

            }

            if (!fieldAuthenticated)
            {
                ViewData["ErrorDetails"] = Resources.Message.E0001;
            }

            return fieldAuthenticated;
        }

        public ActionResult DoLogOff()
        {
            string endSess = Session.SessionID;

            this.ExpireCookie(".ASPXAUTH");
            this.ExpireCookie("AccessibleMenus");
            SessionManager.ClearAll(Session);
            SessionManager.Destroy(Session);

            return Redirect("/Administration/Authenticate");
        }


        [NonAction()]
        private bool Login(string username, string pass)
        {
            if (username == null)
                throw new ArgumentNullException("userName");

            if (username == string.Empty)
                throw new ArgumentException("userName");

            if (pass == null)
                throw new ArgumentNullException("password");

            if (pass == string.Empty)
                throw new ArgumentException("password");


            var strDBHash = string.Empty;
            var strDBSalt = string.Empty;
            var logonUser = auDao.GetUserByName(username);

            if (logonUser == null) return false;

            bool isLogin = false;
            if (logonUser.Password.Trim().Equals(Constants.encryptDataMd5(pass, 4)))
            {
                isLogin = true;
            }
            return isLogin;
        }

        [NonAction()]
        private void DoLogin(UserAdmin user)
        {
            int sessionTimeout = 400;
            UserData ud = new UserData(user.UserAdminId, user.UserName, 0);

            //put user data to authentication ticket
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(sessionTimeout), false, ud.ToXml());
            //Encrypt ticket
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            //Add to cookie
            HttpCookie authCookie = new HttpCookie(Constants.SERVER_COOKIE, encryptedTicket);
            Response.Cookies.Add(authCookie);
            //FormsIdentity identity = new FormsIdentity(authTicket);                         
            //AuthenticationProjectPrincipal principal = new AuthenticationProjectPrincipal(identity, ud);
            //HttpContext.User = principal;

            ////invalidate cookie
            //InvalidateModulesCookie();
        }

        [NonAction()]
        private void InvalidateModulesCookie()
        {
            HttpCookie cookie = HttpContext.Request.Cookies["AccessibleMenus"];
            if (cookie != null)
            {
                cookie.Expires = new DateTime(1970, 1, 1);
                HttpContext.Response.Cookies.Add(cookie);
            }
        }

        [NonAction()]
        private void ExpireCookie(string cookieName)
        {
            if (Request.Cookies[cookieName] != null)
            {
                HttpCookie cookie = new HttpCookie(cookieName);
                cookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(cookie);
            }
        }

        #endregion
    }
}
